const jwt = require("jsonwebtoken");
const dotenv = require("dotenv");
import express, { Request, Response, NextFunction } from "express";
import config from '@/config/routes-config'

dotenv.config();
// Token 校验中间件
const checkToken = (req: Request, res: Response, next: NextFunction) => {

  console.log('req.path>>', req.path)
  // 从配置中匹配当前请求的路径和方法
  const routeMatch =  config.protectedRoutes.some(
    (route) => {
      if (route.path.includes('*')) {
        const baseRoute = route.path.replace('*', '');
        return req.path.startsWith(baseRoute);
      }
      return route.path === req.path && route.method === req.method
    }
  );

  // 如果不需要校验 Token，直接跳过
  if (routeMatch) {
    return next();
  }

  const token = req.headers["authorization"]; // 从请求头获取 token

  if (!token) {
    res.status(401).json({ message: 'Token is required' });
    return;
  }
  // 验证 Token
  jwt.verify(token, process.env.JWT_SECRET_KEY!, (err:any, decoded:any) => {
    if (err) {
      res.status(401).json({ message: 'Invalid or expired token' });
      return;
    }

    // 将解码后的用户信息挂载到 req.user
    (req as any).user = decoded;
    next(); // 继续执行后续逻辑
  });
};

export {
    checkToken
};
